package com.hunttown.mes.manage.service;

import com.hunttown.mes.common.utils.FormatUtils;
import com.hunttown.mes.rpc.api.AnalysisVisualCatalogRpcService;
import com.hunttown.mes.rpc.domain.AnalysisVisualCatalogDTO;
import com.hunttown.mes.rpc.domain.query.AnalysisVisualCatalogDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.keys.KeyConstants;
import com.hunttown.mes.common.cache.Cache;
import com.hunttown.mes.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * created by wangjunfu on 2018-12-12 18:11:38
 */
@Service
public class AnalysisCatalogManageService {

    private final static Logger logger = LoggerFactory.getLogger(AnalysisCatalogManageService.class);

    private final AnalysisVisualCatalogRpcService rpcService;
    private final AHelpManageService helpService;
    private final Cache jedisCache;

    @Autowired
    public AnalysisCatalogManageService(AnalysisVisualCatalogRpcService rpcService, AHelpManageService helpService, Cache jedisCache) {
        this.rpcService = rpcService;
        this.helpService = helpService;
        this.jedisCache = jedisCache;
    }

    // 新增
    public AnalysisVisualCatalogDTO insert(AnalysisVisualCatalogDTO objDTO) {
        return rpcService.insert(objDTO);
    }

    // 通过ID修改
    public Boolean updateInfoById(AnalysisVisualCatalogDTO objDTO) {
        Boolean isNext = rpcService.updateInfoById(objDTO);
        if (isNext) {
            // 刷新分类缓存
            refreshNewsCatalogCache(objDTO.getId());
        }
        return isNext;
    }

    // 通过Query修改
    public Boolean updateInfoByQuery(AnalysisVisualCatalogDTOQuery objDTOQuery) {
        Boolean isNext = rpcService.updateInfoByQuery(objDTOQuery);

        //单体刷新
        if (isNext && objDTOQuery.getW_id() != null) {
            refreshNewsCatalogCache(objDTOQuery.getW_id());
        }

        //批量刷新缓存
        if (isNext && objDTOQuery.getIds() != null) {
            List<Integer> list = new ArrayList<>();
            try {
                list = (List<Integer>) objDTOQuery.getIds();
            } catch (Exception e) {
                e.printStackTrace();
            }
            refreshNewsCatalogCacheByIdList(list);
        }
        return isNext;
    }

    // 通过ID删除
    public Boolean delete(Integer id) {
        Boolean isNext = rpcService.deleteById(id);
        if (isNext) {
            // 刷新分类缓存
            refreshNewsCatalogCache(id);
        }
        return isNext;
    }

    // 批量删除
    public Boolean deleteForBatch(String clearIds) {

        //处理 “,5,6,7,” 为List
        List<Integer> idList = FormatUtils.commaToList_Integer(clearIds);

        if (idList.size() == 0) {
            return false;
        }

        AnalysisVisualCatalogDTOQuery query = new AnalysisVisualCatalogDTOQuery();
        query.setDeleteFlag(1);
        query.setIds(idList);

        Boolean isNext = rpcService.updateInfoByQuery(query);
        if (isNext) {
            // 刷新分类缓存
            refreshNewsCatalogCacheByIdList(idList);
        }

        return isNext;
    }

    // 通过ID获取
    public AnalysisVisualCatalogDTO getById(Integer id) {
        if (id == null || id <= 0) {
            return null;
        }
        return rpcService.selectById(id);
    }

    // 通过Query获取
    public AnalysisVisualCatalogDTO getByQuery(AnalysisVisualCatalogDTOQuery objDTOQuery) {
        return rpcService.selectObjByQuery(objDTOQuery);
    }

    // 获取分页列表
    public Page<AnalysisVisualCatalogDTO> getForPage(AnalysisVisualCatalogDTOQuery objDTOQuery) {
        return rpcService.getListForPage(objDTOQuery);
    }

    // 改变某条记录的使用状态
    public Boolean changeState(Integer id, Integer state) {
        AnalysisVisualCatalogDTO obj = new AnalysisVisualCatalogDTO();
        obj.setStopFlag(state);
        obj.setId(id);
        return updateInfoById(obj);
    }

    // 通过模块类型和分类名称获取获取分类
    public AnalysisVisualCatalogDTO getByCateName(int modelType, String name) {
        if (StringUtils.isBlank(name)) {
            return null;
        }

        AnalysisVisualCatalogDTOQuery query = new AnalysisVisualCatalogDTOQuery();
        query.setModelType(modelType);
        query.setCatalogName(name.trim());
        query.setStopFlag(0);
        query.setDeleteFlag(0);

        return getByQuery(query);
    }

    // 通过英文名称获取分类信息
    public AnalysisVisualCatalogDTO getByCateEnName(String enname) {
        AnalysisVisualCatalogDTOQuery query = new AnalysisVisualCatalogDTOQuery();
        query.setCatalogNameEn(enname.trim());
        query.setStopFlag(0);
        query.setDeleteFlag(0);

        return getByQuery(query);
    }

    public AnalysisVisualCatalogDTO getByIdEntId(Integer id, Integer entid) {
        AnalysisVisualCatalogDTOQuery catalogQuery = new AnalysisVisualCatalogDTOQuery();
        catalogQuery.setId(id);
        catalogQuery.setEntId(entid);
        return rpcService.selectObjByQuery(catalogQuery);
    }

    /**
     * 先从缓存中获取数据
     * 如果缓存为空，从数据库中获取，并将获取的数据添加到缓存。
     *
     * @param id id
     * @return obj
     */
    public AnalysisVisualCatalogDTO getFromCacheId(Integer id) {
        if (id == null || id <= 0) {
            return null;
        }

        AnalysisVisualCatalogDTO obj = jedisCache.oget(KeyConstants.NEWSCATALOG_INFO_KEY_ID + id, AnalysisVisualCatalogDTO.class);
        if (obj == null) {
            obj = getById(id);
            if (obj != null) {
                jedisCache.oset(KeyConstants.NEWSCATALOG_INFO_KEY_ID + id, obj);
            }
        }

        return obj;
    }

    /**
     * 从缓存中获取数据
     *
     * @param enname 分类英文名称
     * @return obj
     */
    public AnalysisVisualCatalogDTO getByFromCacheEnname(String enname) {
        if (StringUtils.isBlank(enname)) {
            return null;
        }

        //不同企业下可能存在相同的分类，因此KEY会相同
        String key = enname + "_" + helpService.getEnterpriseId();

        AnalysisVisualCatalogDTO obj = jedisCache.oget(KeyConstants.NEWSCATALOG_INFO_KEY_ENNAME + key, AnalysisVisualCatalogDTO.class);
        if (obj == null) {
            obj = getByCateEnName(enname);
            if (obj != null) {
                jedisCache.oset(KeyConstants.NEWSCATALOG_INFO_KEY_ENNAME + key, obj);
            }
        }

        return obj;
    }

    //region 刷新缓存

    /**
     * 刷分类缓存
     *
     * @param id id
     */
    public void refreshNewsCatalogCache(Integer id) {
        if (id == null || id <= 0) {
            return;
        }

        AnalysisVisualCatalogDTO obj = getById(id);
        if (obj != null) {
            jedisCache.delete(KeyConstants.NEWSCATALOG_INFO_KEY_ID + id);
            jedisCache.delete(KeyConstants.NEWSCATALOG_INFO_KEY_ENNAME + obj.getCatalogNameEn() + "_" + obj.getEntId());

            //刷新首页分类
            jedisCache.delete(KeyConstants.INDEXCATE_LIST_KEY + obj.getEntId());
        }
    }

    /**
     * 刷分类缓存(批量)
     *
     * @param idList
     */
    public void refreshNewsCatalogCacheByIdList(List<Integer> idList) {
        if (idList == null || idList.size() == 0) {
            return;
        }

        for (Integer id : idList) {
            refreshNewsCatalogCache(id);
        }
    }
    //endregion

    //region 整理结构

    /**
     * 通过递归得到树形结构
     *
     * @param list
     * @param parentId
     * @param splitMark
     * @return
     */
    public List<AnalysisVisualCatalogDTO> getListByRecursion(List<AnalysisVisualCatalogDTO> list, Integer parentId, String splitMark) {
        List<AnalysisVisualCatalogDTO> returnList = new ArrayList<>();

        if (parentId > 0) {
            if (splitMark.equals("|")) {
                splitMark += "┄";
            } else {
                splitMark += " ┄";
            }
        }

        if (list != null && list.size() > 0) {
            List<AnalysisVisualCatalogDTO> mainList = list.stream().filter(s -> s.getParentId().equals(parentId)).collect(Collectors.toList());

            for (AnalysisVisualCatalogDTO item : mainList) {
                if (parentId > 0) {
                    item.setCatalogName(String.format("%s %s", splitMark, item.getCatalogName()));
                }
                returnList.add(item);

                List<AnalysisVisualCatalogDTO> next_list = getListByRecursion(list, item.getId(), splitMark);
                for (AnalysisVisualCatalogDTO item_child : next_list) {
                    returnList.add(item_child);
                }
            }
        }

        return returnList;
    }

    /**
     * 通过递归获取当前对象的最顶级ID
     *
     * @param id ID
     * @return
     */
    public Integer getRootIdByRecursion(Integer id) {
        if (id == null || id <= 0) {
            return id;
        }

        Integer result = id;

        AnalysisVisualCatalogDTO obj = getById(id);

        if (obj.getParentId() > 0) {
            result = getRootIdByRecursion(obj.getParentId());
        } else {
            result = obj.getId();
        }

        return result;
    }

    /**
     * 通过递归获取当前id 数据及他所有子分类数据
     * 返回 List 对象
     *
     * @param id          分类ID
     * @param needGetCurr 是否获取当前id 的数据
     * @return
     */
    public List<AnalysisVisualCatalogDTO> getChildListById(Integer id, boolean needGetCurr) {
        List<AnalysisVisualCatalogDTO> returnList = new ArrayList<>();
        if (id == null || id <= 0) {
            return returnList;
        }

        // 获取当前id 的数据
        if (needGetCurr) {
            AnalysisVisualCatalogDTO obj = getById(id);
            if (obj != null) {
                returnList.add(obj);
            }
        }

        AnalysisVisualCatalogDTOQuery query = new AnalysisVisualCatalogDTOQuery();
        query.setParentId(id);
        query.setStopFlag(0);
        query.setPageSize(1000);

        Page<AnalysisVisualCatalogDTO> list = getForPage(query);

        if (list != null && list.getItems().size() > 0) {
            for (AnalysisVisualCatalogDTO item : list.getItems()) {
                returnList.add(item);

                List<AnalysisVisualCatalogDTO> next_list = getChildListById(item.getId(), false);
                returnList.addAll(next_list);
            }
        }

        return returnList;
    }

    /**
     * 通过递归获取当前id 数据及他所有子分类id
     * 返回 List id
     *
     * @param id ID
     * @return
     */
    public List<Integer> getChildIdsByRecursion(Integer id) {
        List<Integer> idList = new ArrayList<>();
        if (id == null || id <= 0) {
            return idList;
        }
        idList.add(id);

        AnalysisVisualCatalogDTOQuery query = new AnalysisVisualCatalogDTOQuery();
        query.setParentId(id);
        query.setStopFlag(0);
        query.setPageSize(1000);

        Page<AnalysisVisualCatalogDTO> childList = getForPage(query);
        if (childList != null && childList.getItems().size() > 0) {
            for (AnalysisVisualCatalogDTO item : childList.getItems()) {
                List<Integer> next_list = getChildIdsByRecursion(item.getId());
                idList.addAll(next_list);
            }
        }

        return idList;
    }

    /**
     * 取出每条记录的子类，一并返回
     *
     * @param list
     * @return
     */
    public List<AnalysisVisualCatalogDTO> getChildrenForEach(List<AnalysisVisualCatalogDTO> list, String mark) {
        if (list == null || list.size() == 0) {
            return list;
        }

        List<AnalysisVisualCatalogDTO> return_list = new ArrayList<>();
        List<AnalysisVisualCatalogDTO> child_list = new ArrayList<>();

        for (AnalysisVisualCatalogDTO item : list) {
            child_list = getChildrenById(item, mark);
            return_list.addAll(child_list);
        }

        return return_list;
    }

    /**
     * 取出每条记录的子类，一并返回（具体实施）
     *
     * @param dto
     * @return
     */
    public List<AnalysisVisualCatalogDTO> getChildrenById(AnalysisVisualCatalogDTO dto, String mark) {
        List<AnalysisVisualCatalogDTO> child_list = new ArrayList<>();
        child_list.add(dto);

        if (mark.equals("|")) {
            mark += "┄";
        } else {
            mark += " ┄";
        }

        AnalysisVisualCatalogDTOQuery query = new AnalysisVisualCatalogDTOQuery();
        query.setParentId(dto.getId());
        query.setStopFlag(0);
        query.setPageSize(1000);
        query.setOrderBy("order by sort desc, id asc");
        Page<AnalysisVisualCatalogDTO> dataPage = getForPage(query);

        if (dataPage != null && dataPage.getItems().size() > 0) {
            for (AnalysisVisualCatalogDTO item : dataPage.getItems()) {
                item.setCatalogName(mark + " " + item.getCatalogName());
                List<AnalysisVisualCatalogDTO> next_list = getChildrenById(item, mark);
                child_list.addAll(next_list);
            }
        }

        return child_list;
    }
    //endregion

    /**
     * 判断英文名称是否存在，不存在则插入
     *
     * @param modelType
     * @param name
     * @param enName
     */
    public void judgeAndInsert(Integer modelType, String name, String enName) {
        if (StringUtils.isBlank(name) || StringUtils.isBlank(enName)) {
            return;
        }

        if (modelType == null || modelType <= 0) {
            return;
        }

        AnalysisVisualCatalogDTOQuery query = new AnalysisVisualCatalogDTOQuery();
        query.setCatalogNameEn(enName.trim());
        query.setDeleteFlag(0);
        AnalysisVisualCatalogDTO obj = getByQuery(query);
        if (obj != null && obj.getId() > 0) {
            return;
        }

        AnalysisVisualCatalogDTO dto = new AnalysisVisualCatalogDTO();
        dto.setParentId(0);
        dto.setCatalogName(name.trim());
        dto.setCatalogNameEn(enName.trim());
        dto.setModelType(modelType);
        dto.setDescription("");
        dto.setIsSystem(0);
        dto.setAdminId(1);
        dto.setCreateTime(new Date());
        dto.setStopFlag(0);
        dto.setDeleteFlag(0);
        insert(dto);
    }

    //region 模糊搜索分类
    public List<Map<String, String>> getSimilarCatalog(String similar, Integer modelType) {
        return rpcService.selectSimilarCatalog(similar, modelType);
    }
    //endregion

    //region Description相关操作

    /**
     * 将description的值取出来，组成一个List
     *
     * @param modelType 模块
     * @return list
     */
    public List<String> getDescriptionList(Integer modelType) {
        AnalysisVisualCatalogDTOQuery query = new AnalysisVisualCatalogDTOQuery();
        query.setModelType(modelType);
        query.setPageSize(1000);
        query.setStopFlag(0);
        Page<AnalysisVisualCatalogDTO> page = getForPage(query);

        List<String> list = new ArrayList<>();
        for (AnalysisVisualCatalogDTO item : page.getItems()) {
            if (StringUtils.isBlank(item.getDescription())) {
                continue;
            }

            if (list.contains(item.getDescription())) {
                continue;
            }

            list.add(item.getDescription());
        }

        return list;
    }

    /**
     * 根据description获取ID集合
     *
     * @param des des名称
     * @return list
     */
    public List<Integer> getIdsByDescription(String des) {
        List<Integer> list = new ArrayList<>();
        if (StringUtils.isBlank(des) || des.equals("-9999")) {
            return list;
        }

        AnalysisVisualCatalogDTOQuery query = new AnalysisVisualCatalogDTOQuery();
        query.setDescription(des);
        query.setPageSize(1000);
        query.setStopFlag(0);
        Page<AnalysisVisualCatalogDTO> page = getForPage(query);

        for (AnalysisVisualCatalogDTO item : page.getItems()) {
            list.add(item.getId());
        }

        return list;
    }
    //endregion
}